package vip.aster.generator.controller;

import cn.hutool.core.io.IoUtil;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;
import vip.aster.common.utils.ResultInfo;
import vip.aster.generator.service.GeneratorService;
import vip.aster.generator.vo.PreviewVO;

import java.io.ByteArrayOutputStream;
import java.util.List;
import java.util.zip.ZipOutputStream;

/**
 * 代码生成 控制器
 *
 * @author Aster
 * @since 2024/2/13 11:08
 */
@RestController
@RequestMapping("/gen")
@AllArgsConstructor
@Tag(name = "代码生成")
public class GeneratorController {
    private final GeneratorService generatorService;

    /**
     * 生成代码（zip压缩包）
     */
    @GetMapping("/download")
    public void download(String tableIds, HttpServletResponse response) throws Exception {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zip = new ZipOutputStream(outputStream);

        // 生成代码
        for (String tableId : tableIds.split(",")) {
            generatorService.downloadCode(tableId, zip);
        }

        IoUtil.close(zip);

        // zip压缩包数据
        byte[] data = outputStream.toByteArray();

        response.reset();
        response.setHeader("Content-Disposition", "attachment; filename=\"aster.zip\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");

        IoUtil.write(response.getOutputStream(), false, data);
    }

    /**
     * 生成代码（自定义目录）
     */
    @ResponseBody
    @PostMapping("/code")
    public ResultInfo<String> code(@RequestBody String[] tableIds) throws Exception {
        // 生成代码
        for (String tableId : tableIds) {
            generatorService.generatorCode(tableId);
        }

        return ResultInfo.success();
    }
    /**
     * 预览代码
     */
    @GetMapping("/preview")
    public ResultInfo<List<PreviewVO>> preview(@RequestParam String tableId) throws Exception {
        List<PreviewVO> results = generatorService.preview(tableId);
        return ResultInfo.success(results);
    }
}
